package yanyan.com.tochar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.gs.buluo.common.widget.LoadingDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import yanyan.com.tochar.beans.ToChanrBean;
import yanyan.com.tochar.gif.ImageUtil;
import yanyan.com.tochar.utils.BitmapPixelUtil;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.PictureSelectUtil;
import yanyan.com.tochar.utils.ProgressDiaolog;
import yanyan.com.tochar.utils.ToCharUtil;
import yanyan.com.tochar.utils.ToastUtil;

/**
 * 隐藏图
 */
public class FunsHiddenImgActivity extends Activity {
    private ImageView showImg,hiddenImg,resImg;
    private Bitmap showBitmap,hiddenBitmap;
    private Bitmap resBitmap;
    private ProgressDialog p;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_hidden);
        showImg=findViewById(R.id.hidden_select_show);
        hiddenImg=findViewById(R.id.hidden_select_hidden);
        resImg=findViewById(R.id.hidden_res);

        //统计各功能
        CoreUtil.statisticalFuns(this,"funs_hidden_img");
    }


    /**
     * 显示图
     * @param view
     */
    public void selectShow(View view){
        PictureSelectUtil.selectPohto(this,3306);
    }

    /**
     * 隐藏图
     * @param view
     */
    public void selectHidden(View view){
        PictureSelectUtil.selectPohto(this,3307);
    }


    public void getHiddenImg(View view) {
        if (showBitmap == null) {
            ToastUtil.showShotToast(this, "请选择上层图片");
            return;
        }
        if (hiddenImg == null) {
            ToastUtil.showShotToast(this, "请选择下层图片");
            return;
        }

        LoadingDialog.getInstance().show(FunsHiddenImgActivity.this, "正在生成", false);//加载
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                try {
                    resBitmap = generateImg();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            resImg.setImageBitmap(resBitmap);
                        }
                    });
                    e.onComplete();
                } catch (Exception e1) {
                    e.onError(e1);
                }

            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {

            }

            @Override
            public void onError(Throwable e) {
                LoadingDialog.getInstance().dismissDialog();
                ToastUtil.showShotToast(FunsHiddenImgActivity.this, "生成失败");
            }

            @Override
            public void onComplete() {
                LoadingDialog.getInstance().dismissDialog();
                ToastUtil.showShotToast(FunsHiddenImgActivity.this, "生成成功");
            }
        });
    }

    public void savenHiddenImg(View view){
        if(resImg!=null){
            String path= PictureSelectUtil.savePhotoToSD(resBitmap,FunsHiddenImgActivity.this);
            ToastUtil.showShotToast(FunsHiddenImgActivity.this,"图片已保存至"+path);
        }else {
            ToastUtil.showShotToast(FunsHiddenImgActivity.this,"您还没有生成");
        }

    }

    public Bitmap generateImg(){
        int b_width = hiddenBitmap.getWidth();
       int b_height = hiddenBitmap.getHeight();
        int w_width = showBitmap.getWidth();
       int w_height = showBitmap.getHeight();

       int f_width=Math.max(b_width,w_width);
       int f_height=Math.max(w_height,b_height);
       Bitmap res=Bitmap.createBitmap(f_width,f_height,Bitmap.Config.ARGB_8888);

        //黑色图片距离边缘的距离
        int b_widthOffset = b_width == f_width ? 0 : (f_width - b_width) / 2;
        int b_heightOffset = b_height == f_height ? 0 : (f_height - b_height) / 2;
        //白色图片离边缘距离
        int w_widthOffset = w_width == f_width ? 0 : (f_width - w_width) / 2;
        int w_heightOffset = w_height == f_height ? 0 : (f_height - w_height) / 2;


       for(int x=0;x<f_width;x++){
           for(int y=0;y<f_height;y++){
               //上下左右交叉排列黑白像素
               boolean blackPixel = (x + y) % 2 == 0 ? true : false;

               int coor_x;
               int coor_y;
               //决定当前像素位置是否对应图一或图二某像素，如果没有，跳过循环
               boolean validPixel = true;
               if (!blackPixel) {
                   coor_x = x - b_widthOffset;
                   if (coor_x > b_width - 1) validPixel = false;
                   coor_y = y - b_heightOffset;
                   if (coor_y > b_height - 1) validPixel = false;
               }else {
                   coor_x = x - w_widthOffset;
                   if (coor_x > w_width - 1) validPixel = false;
                   coor_y = y - w_heightOffset;
                   if (coor_y > w_height - 1) validPixel = false;
               }

               validPixel = validPixel && coor_x >= 0 && coor_y >= 0;
               if (!validPixel) continue;

               //根据颜色计算像素灰度，设定透明度
               if (blackPixel) {
                   int pixel = showBitmap.getPixel(coor_x, coor_y);
                   int red = (pixel & 0xff0000) >> 16;
                   int green = (pixel & 0x00ff00) >> 8;
                   int blue = (pixel & 0x0000ff);
                   int gray = (red * 19595 + green * 38469 + blue * 7472) >> 16;
                   int argb = Color.argb(255 - gray, 0, 0, 0);
                   res.setPixel(x,y,argb);
               }else {
                   int pixel = hiddenBitmap.getPixel(coor_x, coor_y);
                   int red = (pixel & 0xff0000) >> 16;
                   int green = (pixel & 0x00ff00) >> 8;
                   int blue = (pixel & 0x0000ff);
                   int gray = (red * 19595 + green * 38469 + blue * 7472) >> 16;
                   int argb = Color.argb( gray, 255, 255, 255);
                   res.setPixel(x,y,argb);
               }

           }
       }

       return res;
    }







    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            String path="";
            if(localMedias!=null && localMedias.size()>0){
                LocalMedia localMedia = localMedias.get(0);
                if(CoreUtil.isAndroidQ()){
                    path=localMedia.getAndroidQToPath();
                }else {
                    path= localMedia.getPath();
                }
            if(requestCode==3306){
                showBitmap = PictureSelectUtil.getBitmap(path);
                showImg.setImageBitmap(showBitmap);
            }else {
               hiddenBitmap=PictureSelectUtil.getBitmap(path);
               hiddenImg.setImageBitmap(hiddenBitmap);
            }
            }
        }else {
            ToastUtil.showShotToast(this,"图片选择失败");
        }
    }
}
